package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.TreeNode;

/**
 * @Author fengye
 * @Date 2023/4/19 9:24
 **/
public class InsertIntoABinarySearchTree701 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(3)),
                new TreeNode(7));
        new InsertIntoABinarySearchTree701().insertIntoBST(root, 5).print();
    }
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) {
            return new TreeNode(val);
        }

        TreeNode curr = root;
        while (curr != null) {
            // 在左树
            if(val < curr.val) {
                if(curr.left == null) {
                    curr.left = new TreeNode(val);
                    break;
                } else {
                    curr = curr.left;
                }
            } else {
                // 在右树
                if(curr.right == null) {
                    curr.right = new TreeNode(val);
                    break;
                } else {
                    curr = curr.right;
                }
            }
        }

        return  root;
    }
}
